package com.example.listener;

import com.example.service.other.SeckillDlqService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.example.entity.constant.mq.RabbitmqConstant.SECKILL_DL_QUEUE;

// 监听死信队列，处理秒杀时的死信消息
@Component
public class SeckillDlqConsumer {
    @Autowired
    private SeckillDlqService seckillDlqService; // 死信处理服务

    @RabbitListener(queues = SECKILL_DL_QUEUE)
    public void handleSeckillDlqMsg(Message message) {
        // 1. 获取消息内容和属性（区分死信来源）
        String msg = new String(message.getBody());
        String expiration = message.getMessageProperties().getExpiration(); // 过期时间（非null则是过期消息）
        String rejectionReason = message.getMessageProperties().getHeader("x-rejected-reason"); // 拒绝原因（非null则是消费失败）

        // 2. 根据死信来源处理
        if (expiration != null) {
            // 场景1：过期消息 → 取消订单+释放库存
            String orderId = msg.split("_")[2];
            seckillDlqService.cancelOrderAndReleaseStock(orderId);
        } else if (rejectionReason != null) {
            // 场景2：消费失败消息 → 记录日志+标记待重试
            seckillDlqService.recordFailedMsgAndMarkRetry(msg, rejectionReason);
        } else {
            // 场景3：队列满员消息 → 记录峰值流量日志
            seckillDlqService.recordQueueFullMsg(msg);
        }
    }
}
